package com.example.controller;

import com.example.pojo.Result;
import com.example.pojo.overtimeMonitoringPojo;
import com.example.service.overtimeMonitoringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class overtimeMonitoringController {

    @Autowired
    private overtimeMonitoringService overtimeMonitoringService;

    // 原有的全量查询接口
    @PostMapping("/queryOvertimeMonitoring")
    public Result queryOvertimeMonitoring() {
        List<overtimeMonitoringPojo> overtimeMonitoringPojoList = overtimeMonitoringService.queryAll();
        System.out.println("Query successful");
        return Result.success(overtimeMonitoringPojoList);
    }

    // 新增分页查询接口
    @PostMapping("/queryOvertimeMonitoringByPage")
    public Result queryOvertimeMonitoringByPage(@RequestBody Map<String, Object> params) {
        try {
            Integer page = (Integer) params.get("page");
            Integer pageSize = (Integer) params.get("pageSize");

            if (page == null || page < 1) {
                page = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 100;
            }

            // 计算起始位置
            int offset = (page - 1) * pageSize;

            // 查询分页数据
            List<overtimeMonitoringPojo> overtimeMonitoringPojoList =
                    overtimeMonitoringService.queryByPage(offset, pageSize);

            // 查询总记录数
            int total = overtimeMonitoringService.queryTotalCount();

            Map<String, Object> result = new HashMap<>();
            result.put("list", overtimeMonitoringPojoList);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);

            System.out.println("分页查询成功: 第" + page + "页, 每页" + pageSize + "条, 总计" + total + "条记录");
            return Result.success(result);
        } catch (Exception e) {
            System.out.println("分页查询失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "分页查询失败"); // 假设500是错误代码
        }
    }

    @PostMapping("/insertOvertimeMonitoring")
    public Result insertOvertimeMonitoring(@RequestBody overtimeMonitoringPojo overtimeMonitoringPojo) {
        System.out.println(overtimeMonitoringPojo);
        overtimeMonitoringService.insertOne(overtimeMonitoringPojo);
        System.out.println("Addition successful");
        return Result.success();
    }
}
